<template>
  <div class="page-container">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑健身目标' : '添加健身目标' }}</h2>
      <p>{{ isEdit ? '修改您的健身目标信息' : '设定一个新的健身目标' }}</p>
    </div>
    
    <el-card class="form-card">
      <el-form 
        ref="formRef" 
        :model="goalForm" 
        :rules="rules" 
        label-width="100px"
        class="goal-form"
      >
        <!-- 基本信息 -->
        <h3 class="form-section-title">基本信息</h3>
        
        <el-form-item label="目标标题" prop="title">
          <el-input
            v-model="goalForm.title"
            placeholder="输入目标标题，如'减重5公斤'"
          />
        </el-form-item>
        
        <el-form-item label="目标类型" prop="type">
          <el-select
            v-model="goalForm.type"
            placeholder="选择目标类型"
            style="width: 100%"
            @change="handleTypeChange"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="目标描述" prop="description">
          <el-input
            v-model="goalForm.description"
            type="textarea"
            :rows="3"
            placeholder="详细描述您的目标（可选）"
          />
        </el-form-item>
        
        <!-- 目标数值 -->
        <h3 class="form-section-title">目标数值</h3>
        
        <el-form-item label="目标数值" prop="targetValue">
          <el-input
            v-model="goalForm.targetValue"
            placeholder="输入数值，如'5'"
            type="number"
            style="width: 70%"
          >
            <template #append>
              <el-input v-model="goalForm.unit" placeholder="单位" style="width: 80px" />
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item v-if="showFrequency" label="频率设置" required>
          <div class="frequency-container">
            <span>每</span>
            <el-select v-model="goalForm.frequencyUnit" style="width: 100px; margin: 0 10px">
              <el-option
                v-for="item in frequencyUnitOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-input-number
              v-model="goalForm.frequency"
              :min="1"
              style="width: 100px; margin: 0 10px"
            />
            <span>次</span>
          </div>
        </el-form-item>
        
        <el-form-item label="初始进度" prop="progress">
          <el-slider
            v-model="goalForm.progress"
            :min="0"
            :max="100"
            :step="1"
            show-input
          />
        </el-form-item>
        
        <!-- 时间设置 -->
        <h3 class="form-section-title">时间设置</h3>
        
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker
            v-model="goalForm.startDate"
            type="datetime"
            placeholder="选择开始日期和时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="new Date(2000, 0, 1, 0, 0, 0)"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="目标日期" prop="targetDate">
          <el-date-picker
            v-model="goalForm.targetDate"
            type="datetime"
            placeholder="选择目标完成日期和时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="new Date(2000, 0, 1, 23, 59, 59)"
            style="width: 100%"
            :disabled-date="disabledDate"
          />
        </el-form-item>
        
        <el-form-item v-if="isEdit" label="目标状态" prop="status">
          <el-select
            v-model="goalForm.status"
            placeholder="选择目标状态"
            style="width: 100%"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  createFitnessGoal,
  updateFitnessGoal,
  getFitnessGoalById
} from '@/api/fitnessGoal'

const router = useRouter()
const route = useRoute()
const formRef = ref(null)
const loading = ref(false)

// 判断是否为编辑模式
const isEdit = computed(() => {
  return route.params.id !== undefined
})
const formatDateToYMDHMS = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
// 表单数据
const goalForm = ref({
  title: '',
  type: '',
  description: '',
  targetValue: '',
  unit: '',
  startDate: formatDateToYMDHMS(new Date),
  targetDate: '',
  progress: 0,
  status: 'ACTIVE',
  frequency: 3,
  frequencyUnit: 'WEEK'
})

// 默认单位映射
const defaultUnits = {
  'WEIGHT_LOSS': 'kg',
  'EXERCISE_FREQUENCY': '次',
  'DISTANCE': 'km',
  'STRENGTH': 'kg',
  'ENDURANCE': '分钟',
  'CUSTOM': ''
}

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入目标标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符之间', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择目标类型', trigger: 'change' }
  ],
  targetValue: [
    { required: true, message: '请输入目标数值', trigger: 'blur' }
  ],
  startDate: [
    { required: true, message: '请选择开始日期', trigger: 'change' }
  ],
  targetDate: [
    { required: true, message: '请选择目标完成日期', trigger: 'change' }
  ]
}

// 目标类型选项
const typeOptions = [
  { value: 'WEIGHT_LOSS', label: '减重目标' },
  { value: 'EXERCISE_FREQUENCY', label: '运动频率' },
  { value: 'DISTANCE', label: '距离目标' },
  { value: 'STRENGTH', label: '力量目标' },
  { value: 'ENDURANCE', label: '耐力目标' },
  { value: 'CUSTOM', label: '自定义' }
]

// 状态选项
const statusOptions = [
  { value: 'ACTIVE', label: '进行中' },
  { value: 'COMPLETED', label: '已完成' },
  { value: 'FAILED', label: '未达成' },
  { value: 'ABANDONED', label: '已放弃' }
]

// 频率单位选项
const frequencyUnitOptions = [
  { value: 'DAY', label: '天' },
  { value: 'WEEK', label: '周' },
  { value: 'MONTH', label: '月' }
]

// 是否显示频率设置
const showFrequency = computed(() => {
  return goalForm.value.type === 'EXERCISE_FREQUENCY'
})

// 禁用早于开始日期的日期
const disabledDate = (time) => {
  if (!goalForm.value.startDate) return false
  
  const startDate = new Date(goalForm.value.startDate)
  return time.getTime() < startDate.getTime()
}

// 处理类型变更
const handleTypeChange = (type) => {
  goalForm.value.unit = defaultUnits[type] || ''
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    loading.value = true
    
    try {
      // 目标类型为运动频率时，确保单位设置正确
      if (goalForm.value.type === 'EXERCISE_FREQUENCY') {
        goalForm.value.unit = goalForm.value.unit || '次'
      }
      
      // 准备提交数据
      const submitData = {
        title: goalForm.value.title,
        type: goalForm.value.type,
        description: goalForm.value.description,
        targetValue: goalForm.value.targetValue,
        unit: goalForm.value.unit,
        startDate: goalForm.value.startDate,
        targetDate: goalForm.value.targetDate,
        progress: goalForm.value.progress,
        status: goalForm.value.status,
        frequency: goalForm.value.type === 'EXERCISE_FREQUENCY' ? goalForm.value.frequency : null,
        frequencyUnit: goalForm.value.type === 'EXERCISE_FREQUENCY' ? goalForm.value.frequencyUnit : null
      }
      
      if (isEdit.value) {
        await updateFitnessGoal(route.params.id, submitData)
        ElMessage.success('健身目标更新成功')
      } else {
        await createFitnessGoal(submitData)
        ElMessage.success('健身目标添加成功')
      }
      
      goBack()
    } catch (error) {
      console.error('保存健身目标失败:', error)
      ElMessage.error('保存健身目标失败')
    } finally {
      loading.value = false
    }
  })
}

// 返回列表页
const goBack = () => {
  router.push('/fitness-goals')
}

// 加载目标详情（编辑模式）
const loadGoalDetails = async (id) => {
  loading.value = true
  
  try {
    const goal = await getFitnessGoalById(id)
    
    goalForm.value = {
      title: goal.title,
      type: goal.type,
      description: goal.description || '',
      targetValue: goal.targetValue,
      unit: goal.unit || '',
      startDate: goal.startDate,
      targetDate: goal.targetDate,
      progress: goal.progress || 0,
      status: goal.status,
      frequency: goal.frequency || 3,
      frequencyUnit: goal.frequencyUnit || 'WEEK'
    }
  } catch (error) {
    console.error('获取健身目标失败:', error)
    ElMessage.error('获取健身目标失败')
    router.push('/fitness-goals')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  if (isEdit.value) {
    loadGoalDetails(route.params.id)
  }
})
</script>

<style scoped>
.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 10px 0;
  font-weight: 500;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.form-card {
  margin-bottom: 20px;
}

.goal-form {
  max-width: 600px;
  margin: 0 auto;
}

.form-section-title {
  margin: 25px 0 15px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  color: #409EFF;
  font-weight: 500;
  font-size: 16px;
}

.frequency-container {
  display: flex;
  align-items: center;
}

@media (max-width: 768px) {
  .frequency-container {
    flex-wrap: wrap;
    gap: 10px;
  }
}
</style> 